package com.training.admin.web.controller.report;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.collections.CollectionUtils;
import org.eclipse.jetty.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.demo2do.core.entity.page.Page;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.utils.WebUtils;
import com.training.admin.entity.principal.Principal;
import com.training.admin.entity.project.ProjectTrainee;
import com.training.admin.entity.project.TrainingResult;
import com.training.admin.entity.search.ProjectTraineeReportSearch;
import com.training.admin.entity.security.Login;
import com.training.admin.service.PrincipalService;
import com.training.admin.service.ReportService;
import com.training.admin.service.TrainingCategoryService;
import com.training.admin.service.TrainingResultService;
import com.training.admin.web.controller.view.ExcelTemplateView;
/**
 * 
 * @author sjh
 *
 */
@Controller
@RequestMapping("")
@MenuSetting("menu-report")
public class ProjectTraineeReportController {
    
    private static final Logger logger = LoggerFactory.getLogger(ProjectTraineeReportController.class);
    
	@Autowired
	private TrainingCategoryService trainingCategoryService;
	@Autowired
	private PrincipalService principalService;

	@Autowired
	private ReportService reportService;
	@Autowired
	private TrainingResultService trainingResultService;
	

	/**
	 * 项目学员表
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/project-trainees", method = RequestMethod.GET)
	@MenuSetting("submenu-project-trainee")
	@SuppressWarnings("rawtypes")
	public ModelAndView projectTraineeReportSearch(Page page) {
		ModelAndView modelAndView = new ModelAndView("report/project-trainee-report-search");
		// 培训分类
		Map catMap = trainingCategoryService.getAllCategory();
		Map allCatMap = (Map) catMap.get("allCatMap");
		Map allNameIdMap = (Map) catMap.get("allNameIdMap");

		modelAndView.addObject("allCatMap", allCatMap);
		modelAndView.addObject("allNameIdMap", allNameIdMap);

		return modelAndView;
	}

	/**
	 * 项目学员表提交
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/project-trainees", method = RequestMethod.GET, params = "filter")
	@MenuSetting("submenu-project-trainee")
	@SuppressWarnings("rawtypes")
	public ModelAndView onProjectTraineeReportSearch(ProjectTraineeReportSearch projectTraineeReportSearch, Page page,
			HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("report/project-trainee-report");

		Login login = (Login) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Principal principal = principalService.loadByEmail(login.getEmail());
		if (principal.getAuthority().equals("ROLE_SUPER_USER")) {
			// 系统管理员
			// do nothing
		} else if (principal.getAuthority().equals("ROLE_DEPARTMENT_USER")) {
			// 事业部负责人
			projectTraineeReportSearch.setDepartmentId(principal.getDepartmentId());
		}

		int totals = reportService.count(projectTraineeReportSearch);
		if (totals > 0) {

			List projectTraineeList = reportService.search(projectTraineeReportSearch, page.with(totals));
			List<ProjectTrainee> projectTrainees = new ArrayList<ProjectTrainee>();
			for (int i = 0; i < projectTraineeList.size(); i++) {
				ProjectTrainee projectTrainee = (ProjectTrainee) projectTraineeList.get(i);
				// Course course= projectPhaseCourse.getCourse();
				// set survey result / suggestion to each course
				List<TrainingResult> trainingResultList = trainingResultService.listByTraineeAndProject(
						projectTrainee.getTrainee().getId(), projectTrainee.getProject().getId());
				int totalScore = 0;
				Float totalAbsence = (float) 0;
				int j = 0;
				String comment = "";
				boolean resit = false;
				for (; j < trainingResultList.size(); j++) {
					TrainingResult trainingResult = trainingResultList.get(j);
					if (trainingResult.getScore() > 0) {
						totalScore += trainingResult.getScore();
					}
					if (trainingResult.getAbsence() > 0) {
						totalAbsence += trainingResult.getAbsence();
					}
					if (trainingResult.isResit()) {
						resit = true;
					}
					if (!StringUtil.isBlank(trainingResult.getComment())) {
						comment += "    " + trainingResult.getComment();
					}

				}
				if (j > 0) {
					projectTrainee.setScore(Float.valueOf(totalScore / j));
					projectTrainee.setAbsence(totalAbsence);
				}
				projectTrainee.setResit(resit);
				projectTrainee.setComment(comment);
				projectTrainees.add(projectTrainee);
			}

			modelAndView.addObject("projectTrainees", projectTrainees);
			modelAndView.addObject("recordCount", projectTrainees.size());
			modelAndView.addObject("page", page);

		}

		modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));

		return modelAndView;
	}

	/**
	 * 项目学员表 - 导出
	 * 
	 * @param search
	 * @return
	 */
	@RequestMapping(value = "/reports/project-trainee-report-export", method = RequestMethod.GET)
	@MenuSetting("submenu-project-trainee")
	@SuppressWarnings("rawtypes")
	public ModelAndView projectTraineeReportExport(ProjectTraineeReportSearch projectTraineeReportSearch, Page page) {

		ModelAndView modelAndView = new ModelAndView(
				new ExcelTemplateView("project-trainee-result.xls", "project-trainee-report.xls"));
		Login login = (Login) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Principal principal = principalService.loadByEmail(login.getEmail());
		if (principal.getAuthority().equals("ROLE_SUPER_USER")) {
			// 系统管理员
			// do nothing
		} else if (principal.getAuthority().equals("ROLE_DEPARTMENT_USER")) {
			// 事业部负责人
			projectTraineeReportSearch.setDepartmentId(principal.getDepartmentId());
		}

		int totals = reportService.count(projectTraineeReportSearch);
		if (totals > 0) {
		    
		    try {

	            List projectTraineeList = reportService.searchForExport(projectTraineeReportSearch);
	            List<Object[]> projectTrainees = new ArrayList<Object[]>();
	            for (int i = 0; i < projectTraineeList.size(); i++) {
	                ProjectTrainee projectTrainee = (ProjectTrainee) projectTraineeList.get(i);
	                // Course course= projectPhaseCourse.getCourse();
	                // set survey result / suggestion to each course
	                logger.info("trainee id is [{}], projectId is [{}]", projectTrainee.getTrainee().getId(), projectTrainee.getProject().getId());
	                List<TrainingResult> trainingResultList = trainingResultService.listByTraineeAndProject(
	                        projectTrainee.getTrainee().getId(), projectTrainee.getProject().getId());
	                
	                if(CollectionUtils.isNotEmpty(trainingResultList)) {
	                    int totalScore = 0;
	                    Float totalAbsence = (float) 0;
	                    int j = 0;
	                    String comment = "";
	                    boolean resit = false;
	                    for (; j < trainingResultList.size(); j++) {
	                        TrainingResult trainingResult = trainingResultList.get(j);
	                        if (trainingResult.getScore() > 0) {
	                            totalScore += trainingResult.getScore();
	                        }
	                        if (trainingResult.getAbsence() > 0) {
	                            totalAbsence += trainingResult.getAbsence();
	                        }
	                        if (trainingResult.isResit()) {
	                            resit = true;
	                        }
	                        if (!StringUtil.isBlank(trainingResult.getComment())) {
	                            comment += "    " + trainingResult.getComment();
	                        }

	                    }
	                    if (j > 0) {
	                        projectTrainee.setScore(Float.valueOf(totalScore / j));
	                        projectTrainee.setAbsence(totalAbsence);
	                    }
	                    projectTrainee.setResit(resit);
	                    projectTrainee.setComment(comment);
	                    
	                    
	                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	                    String completeStr = projectTrainee.getComplete() == null ? "" : projectTrainee.getComplete() ? "是" : "否";
	                    String resitStr = projectTrainee.getResit() == null ? "" : projectTrainee.getResit() ? "是" : "否";

	                    projectTrainees.add(new Object[] { projectTrainee.getProject().getCode(),
	                            projectTrainee.getProject().getFirstCategory().getName() + "-" + projectTrainee.getProject().getSecondCategory().getName(),
	                            projectTrainee.getProject().getName(),
	                            projectTrainee.getTrainee().getName(),
	                            projectTrainee.getTrainee().getCode(),
	                            projectTrainee.getTrainee().getEmail(),
	                            projectTrainee.getProject().getBeginDate() == null ? null : dateFormat.format(projectTrainee.getProject().getBeginDate()),
	                            projectTrainee.getProject().getEndDate() == null ? null : dateFormat.format(projectTrainee.getProject().getEndDate()),
	                            completeStr,
	                            resitStr,
	                            projectTrainee.getScore(),
	                            projectTrainee.getAbsence(),
	                            projectTrainee.getComment() });
	                }
	                
	            }
	            modelAndView.addObject("results", projectTrainees);
	            
		    } catch (Exception e) {
		        logger.error("get result error", e);
		        modelAndView.addObject("results", new ArrayList<Object[]>());
		    }
		}

		return modelAndView;

	}
}
